<template>
  <div class="main">
    <div class="air-column">
      <h2>乘机人</h2>
      <!--  :model="{users}" -->
      <el-form class="member-info" :model="{users}">
        <div class="member-info-item" v-for="(item,index) in users" :key="index">
          <el-form-item
            label="乘机人类型"
            :prop="`users[${index}].username`"
            :rules="[{ required: true, message: '姓名不能为空', trigger: 'blur'}]"
          >
            <el-input placeholder="姓名" class="input-with-select" v-model="item.username">
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="成人" value="1"></el-option>
              </el-select>
            </el-input>
          </el-form-item>

          <el-form-item
            label="证件类型"
            :prop="`users[${index}].id`"
            :rules="[{ required: true, message: '证件号码不能为空', trigger: 'blur'},
            {pattern:/^[1-9]\d{16}[0-9Xx]$/,message:'请输入18位身份证号码',trigger: 'blur'}
            ]"
          >
            <!-- pattern:不用加引号 -->
            <el-input placeholder="证件号码" class="input-with-select" v-model="item.id">
              <el-select slot="prepend" value="1" placeholder="请选择">
                <el-option label="身份证" value="1" :checked="true"></el-option>
              </el-select>
            </el-input>
          </el-form-item>
          <!--删除乘机人  -->
          <span class="delete-user" @click="handleDeleteUser(index)">-</span>
        </div>
      </el-form>

      <el-button class="add-member" type="primary" @click="handleAddUsers">添加乘机人</el-button>
    </div>

    <div class="air-column">
      <h2>保险</h2>
      <div>
        <!-- 如果使用筛选框组，可以为复选框组添加一个v-model的绑定，那么后期组中的所有被选中的复选框的label值会自动的添加到这个v-model的绑定数组中 -->
        <el-checkbox-group v-model="insurances">
          <div class="insurance-item" v-for="(item,index) in ticketData.insurances" :key="index">
            <!-- el-checkbox 的 label属性是该 checkbox 对应的值 ，从label中获取对应的保险id-->
            <el-checkbox
              :label="item.id"
              border
            >{{`${item.type}：￥${item.price}/份×1 最高赔付${item.compensation}`}}</el-checkbox>
            <!-- `${item.type}：￥${item.price}/份×1  最高赔付${item.compensation}` -->
          </div>
        </el-checkbox-group>
      </div>
    </div>

    <div class="air-column">
      <h2>联系人</h2>
      <div class="contact">
        <el-form label-width="80px" :model="contactForm" :rules="contactRules" ref="contactForm">
          <el-form-item label="姓名" prop="contactName">
            <el-input v-model="contactForm.contactName" @focus="cleanValid('contactName')"></el-input>
          </el-form-item>

          <el-form-item label="手机" prop="contactPhone">
            <el-input
              placeholder="请输入号码"
              v-model="contactForm.contactPhone"
              @focus="cleanValid('contactPhone')"
            >
              >
              <template slot="append">
                <el-button
                  @click="handleSendCaptcha"
                  :disabled="time == 12 ? false : true"
                >{{timeState}}</el-button>
              </template>
            </el-input>
          </el-form-item>

          <el-form-item label="验证码" prop="captcha">
            <el-input v-model="contactForm.captcha" @focus="cleanValid('captcha')">></el-input>
          </el-form-item>
        </el-form>
        <el-button type="warning" class="submit" @click="handleSubmit">提交订单</el-button>
      </div>
    </div>
    <!-- 使用隐藏域，必须人为调用computed的方法 -->
    <input type="hidden" :value="calcPrice" />
  </div>
</template>

<script>
export default {
  props: ['ticketData'],   //接收父组件 order.vue 传过来的选定机票信息  
  data() {
    return {
      users: [  // 定义 乘机人表单的数据，由于可添加乘机人，乘机人应该是多个-数组存储
        {
          username: '',     //姓名
          id: ''           //身份证 
        },
      ],
      insurances: [],   //获取保险复选框组 选中的值
      contactForm: {
        contactName: '',   //联系人名字
        contactPhone: '',  //联系人手机号
        captcha: '',        //验证码
      },
      time: 12,           //验证码倒计时
      timeState: '发送验证码',
      invoice: false,      //是否需要发票    
      //验证联系人规则
      contactRules: {
        contactName:
          [{ required: true, message: '姓名不能为空', trigger: 'blur' },],
        contactPhone:
          [{ required: true, message: '手机号不能为空', trigger: 'blur' },
          { pattern: /^1[135789]\d{9}$/, message: '请输入正确的格式', trigger: 'blur' }],
        captcha:
          [{ required: true, message: '验证码不能为空', trigger: 'blur' },
          { pattern: /^\d{6}$/, message: '请输入6位数的验证码', trigger: 'blur' }]
      }
    }
  },
  methods: {
    // 添加乘机人
    handleAddUsers() {
      // 实际上就是 通过 给users数组添加 对象，实现结构添加
      this.users.push({
        username: '',     //姓名
        id: ''           //身份证 
      })
    },

    // 移除乘机人
    handleDeleteUser(index) {
      this.users.splice(index, 1)
    },
    // 发送手机验证码
    handleSendCaptcha() {
      if (!/^1[35789]\d{9}$/.test(this.contactForm.contactPhone)) {
        this.$confirm('手机号码格式错误', '提示', {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        })
        return
      }
      this.countDown();       //开启倒计时
      //   验证通过，发送请求
      this.$axios({
        method: 'post',
        url: '/captchas',
        data: { tel: this.contactForm.contactPhone }
      }).then(res => {
        // console.log(res);
        this.$confirm('你的验证码是：' + res.data.code, '提示'), {
          confirmButtonText: '确定',
          showCancelButton: false,
          type: 'warning'
        }
      })
    },
    //封装验证码倒计时
    countDown() {
      //先判断 当前的时间>0，则进行倒计
      if (this.time > 0) {
        this.time--;
        this.timeState = `${this.time}s后再获取`;
        setTimeout(() => {
          this.countDown();
        }, 1000)
      } else {
        this.time = 12;        //重置时间，才能继续下一次倒计时
        this.timeState = '发送验证码';
        return;
      }
    },
    // 提交订单
    handleSubmit() {
      //调用mutations方法 保存url  --未登录状态下，
      this.$store.commit('user/setBackurl', location.href)  //想要保存的数据就是地址

      //   console.log(this.users);
      //   console.log(this.insurances);
      // 准备好 发送提交订单请求 后台要求的参数  
      let orderData = {
        users: this.users,
        insurances: this.insurances,
        contactName: this.contactForm.contactName,
        contactPhone: this.contactForm.contactPhone,
        captcha: this.contactForm.captcha,            //别忘了验证码这条数据（虽然后台api没有）
        invoice: this.invoice,
        seat_xid: this.$route.query.seat_xid,
        //seat_xid:this.ticketData.seat_infos.seat_xid       //取值方法2  
        air: this.$route.query.id,
      }
      //   console.log(orderData);
      //发送 提交订单请求
      this.$axios({
        method: 'post',
        url: '/airorders',
        // headers: { Authorization: this.$store.state.user.userinfo.token },   //报错1:403 Forbidden  添加token
        headers: { Authorization: 'Bearer ' + this.$store.state.user.userinfo.token },
        data: orderData
      }).then(res => {
        console.log(res);  //订单详情
        this.$message.success('订单生成中，请稍后...');
        setTimeout(() => {
          this.$router.push({ path: "/air/pay", query: { id: res.data.data.id } })
          //加query实现路由跳转携带参数订单的id
        }, 1000)
      })
      //   .catch(err => {
      //     console.dir(err);    //status: 401
      //     const { message } = err.response.data
      //     this.$confirm(message, '提示', {
      //       confirmButtonText: '确定',
      //       showCancelButton: false,
      //       type: 'warning'
      //     })
      //   })
    },
    //清除联系人验证
    cleanValid(propname) {
      this.$refs.contactForm.clearValidate(propname)
    }
  },
  mounted() {
    let captchaBtn = document.querySelector('.captchaBtn');
    console.log(captchaBtn);

    console.log('ticketData数据', this.ticketData);
  },
  computed: {  //计算属性 计算机票总价
    calcPrice() {
      let total = 0; //总价格
      // 计算乘机人总价格
      let count = this.users.length    //乘机人数量
      total += this.ticketData.seat_infos.org_settle_price * count
      // 计算 保险费用 --由于每个险种的价格有可能不一样需要先遍历
      for (let i = 0; i < this.insurances.length; i++) {
        total += this.ticketData.insurances[i].price * count
      }
      //计算 机建+燃油费
      total += this.ticketData.airport_tax_audlet * count
      console.log(total);
      // 子传父 告诉父亲监听
      this.$emit('getPrice', total)
      return total
    }
  }
}
</script>

<style scoped lang="less">
.air-column {
  border-bottom: 1px #ddd dashed;
  padding-bottom: 20px;
  margin-bottom: 20px;
}

.air-column h2 {
  margin-bottom: 20px;
  font-size: 22px;
  font-weight: normal;
}
// 乘机人--输入错误提示
/deep/ .member-info .el-form-item__error {
  left: 130px;
}

/deep/ .el-select .el-input {
  width: 130px;
}

.input-with-select {
  width: 590px;
}

.input-with-select /deep/ .el-input-group__prepend {
  background-color: #fff;
}
.member-info /deep/ .el-form-item {
  margin-bottom: 0;
}

.member-info-item {
  border-bottom: 1px #eee dashed;
  padding-bottom: 20px;
  position: relative;

  &:first-child {
    .delete-user {
      display: none;
    }
  }
}

.add-member {
  margin-top: 20px;
}

.delete-user {
  display: block;
  background: #ddd;
  width: 16px;
  height: 16px;
  font-size: 14px;
  text-align: center;
  line-height: 16px;
  color: #fff;
  cursor: pointer;
  border-radius: 50px;
  position: absolute;
  right: -30px;
  top: 50%;
}

.insurance {
  > div {
    margin-top: 10px;
  }
}

.insurance-item {
  margin-bottom: 20px;
}

.contact {
  /deep/ .el-input {
    width: 50%;
  }
}

.submit {
  margin: 50px auto;
  display: block;
  width: 250px;
  height: 50px;
}
</style>